package main

import (
	"fmt"
	"net/http"
	"html/template"
	"strings"
//	"io"
	"log"
)

func sayHelloName(w http.ResponseWriter,r *http.Request){
	r.ParseForm()//parse parameters
	fmt.Println("--------------------------------------------")
	fmt.Println(r.Form)
	fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
	for k,v:=range r.Form {
		fmt.Println("key: ",k)
		fmt.Println("val: ",strings.Join(v," "))
	}
	fmt.Fprintf(w, "Hello! Let's test form items.")
}

func form(w http.ResponseWriter,r *http.Request){
	fmt.Println("--------------------------------------------")
	fmt.Println("Request Method: ",r.Method)
	fmt.Println("Form data: ",r.Form)
	if r.Method=="GET" {
		t,_:=template.ParseFiles("form_items.gtpl")
		t.Execute(w,nil)
	}else{
		r.ParseForm()
		fmt.Println("username: ",r.Form["username"])
		fmt.Println("password: ",r.Form["password"])
		fmt.Println("interest: ",r.Form["interest"])
		fmt.Println("gender:   ",r.Form["gender"])
		fmt.Println("fruit:    ",r.Form["fruit"])

		fmt.Fprintf(w,"username: %v\n",r.Form["username"])
		fmt.Fprintf(w,"password: %v\n",r.Form["password"])
		fmt.Fprintf(w,"interest: %v\n",r.Form["interest"])
		fmt.Fprintf(w,"gender:   %v\n",r.Form["gender"])
		fmt.Fprintf(w,"fruit:    %v\n",r.Form["fruit"])
	}
}

func main(){
	http.HandleFunc("/",sayHelloName)
	http.HandleFunc("/form",form)
	er:=http.ListenAndServe(":9090",nil)
	if er!=nil{
		log.Fatal("ListenAndServe",er)
	}
}